package com.velvetantler.weather.view.home

import android.content.Context
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.velvetantler.weather.R
import com.velvetantler.weather.adapter.CityListAdapter
import com.velvetantler.weather.bean.CityInfo
import com.velvetantler.weather.eventBusEvent.ChangeCityClickEvent
import org.greenrobot.eventbus.EventBus

class ChangeCityDialog(
    val cityList: List<CityInfo>,
    val currentCity: CityInfo,
    context: Context,
    theme: Int
) :
    BottomSheetDialog(context, theme) {
    init {
        setContentView(R.layout.layout_dialog_change_city)
        initView()
    }

    fun initView() {
        // 绑定视图
        val rv = findViewById<RecyclerView>(R.id.rv_city_list)
        // 设置网格间距
        rv?.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(
                outRect: Rect,
                view: View,
                parent: RecyclerView,
                state: RecyclerView.State
            ) {
                super.getItemOffsets(outRect, view, parent, state)
                outRect.top = 20
            }
        })
        // 绑定layoutManager
        rv?.layoutManager = GridLayoutManager(context, 3)
        // 设置列表数据
        var list = mutableListOf<CityInfo>().apply {
            add(currentCity)
            var filterList = cityList.filter { it.cityName != currentCity.cityName }
            addAll(filterList)
        }
        // 设置适配器
        val cityListAdapter = CityListAdapter(list)
        // 点击事件
        cityListAdapter.setOnClickListener(object : CityListAdapter.OnClickListener {
            override fun onClick(cityInfo: CityInfo) {
                // 发送消息通知点击了哪个城市
                EventBus.getDefault().post(ChangeCityClickEvent(cityInfo))
                // 关闭对话框
                dismiss()
            }

        })
        // 绑定适配器
        rv?.adapter = cityListAdapter
    }
}